﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using InspectionMAC.Algorithm;

namespace InspectionMAC.Forms
{
    public partial class AlgorithmForm : Form
    {
        public static bool isNullFiles;
        private int ZoomStep = 40;
        public AlgorithmForm()
        {
            InitializeComponent();
        }

        private void AlgorithmForm_Load(object sender, EventArgs e)
        {
            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            PicStartPos = pictureBox1.Location;
            PicStartSize = pictureBox1.Size;
            this.pictureBox1.MouseWheel += new MouseEventHandler(this.CameraPb_MouseWheel);
        }
        private void AlgorithmFormClosing(object sender, FormClosingEventArgs e)
        {
            SafeDisposeImage(pictureBox1);
            MacTestForm.algorithm_Form = null;
        }


        private void CameraPb_MouseWheel(object sender, MouseEventArgs e)
        {
            if (pictureBox1 == null || pictureBox1.Image == null) return;

            int x = e.Location.X;
            int y = e.Location.Y;
            int ow = pictureBox1.Width;
            int oh = pictureBox1.Height;
            int VX, VY;  // 因缩放产生的位移矢量

            if (e.Delta > 0) // 放大
            {
                // 第1步
                pictureBox1.Width += ZoomStep;
                pictureBox1.Height += ZoomStep;
                // 第2步
                PropertyInfo pInfo = pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pictureBox1, null);
                // 第3步
                pictureBox1.Width = rect.Width;
                pictureBox1.Height = rect.Height;
            }
            if (e.Delta < 0) // 缩小
            {
                // 防止一直缩成负值
                if (pictureBox1.Width < 900)
                    return;

                pictureBox1.Width -= ZoomStep;
                pictureBox1.Height -= ZoomStep;
                PropertyInfo pInfo = pictureBox1.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic);
                Rectangle rect = (Rectangle)pInfo.GetValue(pictureBox1, null);
                pictureBox1.Width = rect.Width;
                pictureBox1.Height = rect.Height;
            }

            // 第4步，求因缩放产生的位移，进行补偿，实现锚点缩放的效果
            VX = (int)((double)x * (ow - pictureBox1.Width) / ow);
            VY = (int)((double)y * (oh - pictureBox1.Height) / oh);
            pictureBox1.Location = new System.Drawing.Point(pictureBox1.Location.X + VX, pictureBox1.Location.Y + VY);
        }


        private void RestoreOriginalSize()
        {
            if (pictureBox1.Image != null)
            {
                pictureBox1.Image = pictureBox1.Image;
                pictureBox1.Size = PicStartSize;
                pictureBox1.Location = PicStartPos;
            }
        }
        private void SafeDisposeImage(PictureBox pictureBox)
        {
            if (pictureBox.InvokeRequired)
            {
                pictureBox.Invoke(new Action<PictureBox>(SafeDisposeImage), pictureBox);
                return;
            }

            if (pictureBox.Image != null)
            {
                var image = pictureBox.Image;
                pictureBox.Image = null;
                image.Dispose();
            }
        }
        private List<string> _imagePaths = new List<string>();
        private int _currentIndex = -1;
        private List<string> _imageNames = new List<string>();

        private Point PicStartPos = new Point();
        private Size PicStartSize = new Size();
        private void LoadImagesFromFolder(string folderPath)
        {
            _imagePaths.Clear();
            _imageNames.Clear();
            if (!Directory.Exists(folderPath)) return;

            var extensions = new[] { ".jpg", ".jpeg", ".png", ".bmp", ".gif" };

            List<string> tempImagePaths = new List<string>();
            List<string> tempImageNames = new List<string>();

            tempImagePaths = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories)
                                  .Where(f => extensions.Contains(Path.GetExtension(f).ToLowerInvariant()))
                                  .ToList();
            _currentIndex = tempImagePaths.Count > 0 ? 0 : -1;

            DirectoryInfo dir = new DirectoryInfo(folderPath);
            FileInfo[] fileInfo = dir.GetFiles();


            if (fileInfo.Length == 0)
            {
                isNullFiles = true;
                MessageBox.Show("路径中无图片");
            }
            else
            {
                isNullFiles = false;
            }

            foreach (FileInfo item in fileInfo)
            {
                Console.WriteLine(item.Name);
                tempImageNames.Add(item.Name);
            }


            List<int> tempIndex = new List<int>();
            List<int> tempIndex1 = new List<int>();
            for (int i = 0; i < tempImageNames.Count; i++)
            {
                if (tempImageNames[i].Split('_').Length >= 3)
                {
                    if (tempImageNames[i].Split('_')[2] == "A")
                    {
                        tempIndex.Add(i);

                    }
                    else
                    {
                        tempIndex1.Add(i);
                    }
                }
                else
                {
                    tempIndex1.Add(i);
                }
            }
            for (int i = 0; i < tempIndex1.Count; i++)
            {
                _imagePaths.Add(tempImagePaths[tempIndex1[i]]);
                _imageNames.Add(tempImageNames[tempIndex1[i]]);
            }
        }
        private void ShowCurrentImage()
        {
            if (isNullFiles) return;

            if (_currentIndex < 0 || _currentIndex >= _imagePaths.Count) return;

            try
            {
                Console.WriteLine(_imagePaths[_currentIndex]);
                //pictureBox1.Image?.Dispose(); // 释放上一张图片资源
                ImgNameTB.Text = _imageNames[_currentIndex];
                pictureBox1.Image = Image.FromFile(_imagePaths[_currentIndex]);
                Image temp = Image.FromFile(_imagePaths[_currentIndex]);
                AlgorithmModule.ImageHandleBitmap(_imagePaths[_currentIndex]);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"图片加载失败: {ex.Message}");
            }
            RestoreOriginalSize();
        }

        private void PrevBtn_Click(object sender, EventArgs e)
        {
            if (_imagePaths.Count == 0) return;

            // 如果是第一张图片，提示用户
            if (_currentIndex == 0)
            {
                MessageBox.Show("已经是第一张图片了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            _currentIndex = _currentIndex - 1;
            ShowCurrentImage();
        }

        private void NextBtn_Click(object sender, EventArgs e)
        {
            if (_imagePaths.Count == 0) return;

            // 如果是最后一张图片，提示用户
            if (_currentIndex == _imagePaths.Count - 1)
            {
                MessageBox.Show("已经是最后一张图片了！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            _currentIndex = _currentIndex + 1;
            ShowCurrentImage();
        }


        // 选择文件夹按钮
        private void SelectImgFolder()
        {
            using (var dialog = new FolderBrowserDialog())
            {
                dialog.SelectedPath = Application.StartupPath;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    LoadImagesFromFolder(dialog.SelectedPath);
                    ShowCurrentImage();
                }
            }
        }

        private void SelectImgFolderBtn_Click(object sender, EventArgs e)
        {
            SelectImgFolder();
        }

        private void SelectImgBtn_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
                        Console.WriteLine("openFileDialog.FileName: " + openFileDialog.FileName + "    fileInfo: " + fileInfo.Name);
                        ImgNameTB.Text = fileInfo.Name;

                        AlgorithmModule.ImageHandleBitmap(openFileDialog.FileName);
                        //AlgorithmModule.ImageHandleV2(new Bitmap(openFileDialog.FileName));
                        //bitmap = (Bitmap)AlgorithmModule.RectPoints(openFileDialog.FileName, AlgorithmModule.pointsList);

                        //AlgorithmModule_GPU.ImageHandleV2_Opencv(new Bitmap(openFileDialog.FileName));

                        
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"无法打开文件: {ex.Message}");

                    }
                }
            }
            RestoreOriginalSize();
        }

        public static ConcurrentQueue<Bitmap> DisplayQueue = new ConcurrentQueue<Bitmap>();

        private System.Windows.Forms.Timer displayUpdateTimer;
        private void InitializeDisplayTimer()
        {
            displayUpdateTimer = new System.Windows.Forms.Timer();
            displayUpdateTimer.Interval = 100; // 100毫秒更新一次
            displayUpdateTimer.Tick += UpdateDisplay;
            displayUpdateTimer.Start();
        }
        private void UpdateDisplay(object sender, EventArgs e)
        {
            if (DisplayQueue.TryDequeue(out Bitmap bmp1))
            {
                UpdatePictureBox(pictureBox1, bmp1);
            }
        }
        private void UpdatePictureBox(PictureBox pictureBox, Bitmap newImage)
        {
            if (pictureBox.InvokeRequired)
            {
                pictureBox.Invoke(new Action<PictureBox, Bitmap>(UpdatePictureBox), pictureBox, newImage);
                return;
            }

            if (pictureBox.Image != null)
            {
                var oldImage = pictureBox.Image;
                pictureBox.Image = null;
                oldImage.Dispose();
            }

            pictureBox.Image = newImage;
        }

        private void DownloadOriginalImage_Click(object sender, EventArgs e)
        {
            if (_currentIndex < 0 || _currentIndex >= _imagePaths.Count)
            {
                MessageBox.Show("没有可下载的图片！");
                return;
            }

            try
            {
                string sourcePath = _imagePaths[_currentIndex];
                string fileExtension = Path.GetExtension(sourcePath);

                // 生成精确到毫秒的时间戳文件名
                string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff");
                string defaultFileName = $"{timestamp}{fileExtension}";

                using (SaveFileDialog saveDialog = new SaveFileDialog())
                {
                    saveDialog.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
                    saveDialog.FileName = defaultFileName;  // 设置默认文件名
                    saveDialog.Title = "保存原图";

                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        File.Copy(sourcePath, saveDialog.FileName, overwrite: true);
                        MessageBox.Show($"图片已保存到：{saveDialog.FileName}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"下载失败: {ex.Message}");
            }
        }
    }
}
